﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TSV.Areas.Administration.Models;
using TSV.Models.Entities;
using TSV.Models;
using TSV.Library.Common;
using TSV.Library.Attributes;
namespace TSV.Areas.Administration.Controllers
{
    public class CategoryController : BaseController
    {
        private CategoryDao cateDao = new CategoryDao();
        //
        // GET: /Administration/Category/
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Doc)]
        public ActionResult Index()
        {
            ViewData[CommonDataKey.CATEGORY] = new SelectList(cateDao.GetParentList(), "ID", "CategoryName");
            return View();
        }

        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Doc)]
        public ActionResult GetListJQGrid(string name, string categoryId)
        {
            //grid constant => duy hung

            List<Category> parentList = cateDao.GetParentList();

            if (!string.IsNullOrEmpty(categoryId))
            {
                parentList = parentList.Where(c => c.ID == int.Parse(categoryId)).ToList<Category>();
            }

            #region JQGrid Params
            string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
            #endregion

            #region search

            List<Category> categoryList = new List<Category>();

            //append child list
            foreach (Category parent in parentList)
            {
                categoryList.Add(parent);

                List<Category> childList = cateDao.GetChildListByParentId(parent.ID);
                foreach (Category child in childList)
                {
                    child.CategoryName = parent.CategoryName + " --> " + child.CategoryName;
                    categoryList.Add(child);
                }
            }

            string searchName = string.Empty;
            if (!string.IsNullOrEmpty(name.Trim()) && !name.Trim().Equals(Constants.CATEGORY_NAME))
            {
                categoryList = categoryList.Where(c => c.CategoryName.Trim().ToLower().Contains(name.Trim().ToLower())).ToList<Category>();
            }
            #endregion



            int totalRecords = categoryList.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
            int currentPage = CommonFunc.SetJqGridPageIndex(totalRecords, pageIndex, rowCount);
            //var finalList = categoryList;
            var finalList = cateDao.Sort(categoryList, sortColumn, sortOrder)
                                  .Skip((currentPage - 1) * rowCount)
                                   .Take(rowCount);

            var jsonData = new
            {
                total = totalPages,
                page = currentPage,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {
                        i = m.ID,
                        cell = new string[] {
                            m.ID.ToString(),
                            "<img alt=\"Hình\" width=\"50px\" src=\"/FileUpload/Images/Category/" + m.Image + "\"/>",
                            HttpUtility.HtmlEncode(m.CategoryName),                                                                                  
                            string.IsNullOrEmpty(m.Description)? string.Empty: HttpUtility.HtmlEncode(m.Description).Replace("\n","<br/>"),                            
                            m.ParentId.HasValue? string.Empty : "<input type='button' name='btnMoveUp' class='icon moveup' title='Chuyển mẫu tin lên trên' onclick=\"JS_LIB.redirect('/Administration/Category/MoveCategoryUp/?id=" + m.ID.ToString() +"')\" />"
                            +"<input type='button' name='btnMoveDown' class='icon movedown' title='Chuyển mẫu tin xuống dưới' onclick=\"JS_LIB.redirect('/Administration/Category/MoveCategoryDown/?id=" + m.ID.ToString() + "')\"/>", //do reverse because im sorting by asc the order
                            "<input type=\"button\" class=\"icon edit\" title=\"Cập nhật\" onclick=\"JS_LIB.redirect('/Administration/Category/Edit/" + m.ID.ToString() + "')\" />"
                        }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Administration/Collaborator/Create

        //
        // GET: /Administration/Category/Details/5
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Doc)]
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Administration/Category/Create
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Them)]
        public ActionResult Create()
        {
            ViewData[CommonDataKey.PARENT_CATEGORY] = new SelectList(cateDao.GetParentList(), "ID", "CategoryName");
            return View();
        }

        //
        // POST: /Administration/Category/Create

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Them)]
        public ActionResult Create(Category category, FormCollection collection)
        {

            if (string.IsNullOrEmpty(collection["Photograph"]))
            {
                category.Image = "NoImage.jpg";
            }
            else
            {
                category.Image = collection["Photograph"];
            }

            int lastOrder = cateDao.GetLastOrder();
            category.CategoryOrder = lastOrder + 1;
            // TODO: Add update logic here
            Message msg = cateDao.Insert(category);
            if (msg.MsgType == MessageType.Info)
            {
                string tempPathPhoto = Server.MapPath(Constants.UPLOAD_TEMP_PATH + category.Image);
                string iconPathPhoto = Server.MapPath(Constants.PHOTO_PATH_ROOT_CATEGORY + category.Image);
                if (System.IO.File.Exists(tempPathPhoto))
                {
                    System.IO.File.Move(tempPathPhoto, iconPathPhoto);
                }

            }
            ShowMessage(msg);
            // TODO: Add insert logic here
            return RedirectToAction("Index");

        }

        //
        // GET: /Administration/Category/Edit/5
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Sua)]
        public ActionResult Edit(int id)
        {
            Category category = cateDao.GetByID(id);
            if (category.ParentId == null)
            {
                ViewData[CommonDataKey.PARENT_CATEGORY] = new SelectList(cateDao.GetParentListExcludeItself(id), "ID", "CategoryName");
            }
            else
            {
                ViewData[CommonDataKey.PARENT_CATEGORY] = new SelectList(cateDao.GetParentListExcludeItself(id), "ID", "CategoryName", category.ParentId);
            }
            return View(category);
        }

        //
        // POST: /Administration/Category/Edit/5

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Sua)]
        public ActionResult Edit(Category category, FormCollection collection)
        {
            if (string.IsNullOrEmpty(collection["Photograph"]))
            {
                category.Image = "NoImage.jpg";
            }
            else
            {
                category.Image = collection["Photograph"];
            }

            // TODO: Add update logic here
            Message msg = cateDao.Update(category);
            ShowMessage(msg);
            // TODO: Add insert logic here
            return RedirectToAction("Index");
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Xoa)]
        public ActionResult DeleteList(string id)
        {
            Message msg = cateDao.DeleteList(id);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Sua)]
        public ActionResult MoveCategoryUp(string id)
        {
            Category category = cateDao.GetByID(int.Parse(id));
            Message msg = cateDao.MoveCategoryUp(category);
            return RedirectToAction("Index");
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Danh_Muc, Rights = Permissions.Sua)]
        public ActionResult MoveCategoryDown(string id)
        {
            Category category = cateDao.GetByID(int.Parse(id));
            Message msg = cateDao.MoveCategoryDown(category);
            return RedirectToAction("Index");
        }
    }
}
